package com.easylinkin.linkappapi.lobar.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.easylinkin.linkappapi.annotation.CommonOperateLogAnnotate;
import com.easylinkin.linkappapi.common.exceptions.BusinessException;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.common.utils.async.AsyncUtil;
import com.easylinkin.linkappapi.common.utils.excel.ExcelConstant;
import com.easylinkin.linkappapi.common.utils.excel.ExcelTools;
import com.easylinkin.linkappapi.common.utils.io.OutputStreamUtil;
import com.easylinkin.linkappapi.lobar.dto.CompanyTree;
import com.easylinkin.linkappapi.lobar.dto.LaborCompanyProjectDTO;
import com.easylinkin.linkappapi.lobar.dto.excel.ExcelResultDTO;
import com.easylinkin.linkappapi.lobar.entity.LaborCompany;
import com.easylinkin.linkappapi.lobar.entity.LaborCompanyProject;
import com.easylinkin.linkappapi.lobar.service.LaborCompanyProjectService;
import com.easylinkin.linkappapi.operatelog.LogHelper;
import com.easylinkin.linkappapi.operatelog.constant.LogConstant.LogModule;
import com.easylinkin.linkappapi.operatelog.constant.LogConstant.LogOperateType;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * @author: kan yuanfeng
 * @Date: 2020/11/04 11:42
 * @Description: 项目劳务公司管理
 */
@RestController
@RequestMapping("laborCompanyProject")
@Api(tags = "项目劳务公司管理")
public class LaborCompanyProjectController {

    @Autowired
    private LaborCompanyProjectService laborCompanyProjectService;
    @Autowired
    private LinkappUserContextProducer linkappUserContextProducer;

    /**
     * @Description: 增加劳务公司(勾选添加)
     * @author kan yuanfeng
     * @date 2020/11/04 11:42
     */
    @PostMapping
    @ApiOperation("增加劳务公司")
    public RestMessage insert(@RequestBody LaborCompanyProject laborCompanyProject) {
        //todo 参数验证
        laborCompanyProjectService.insert(laborCompanyProject);
        return RestBuilders.successBuilder().build();
    }

    /**
     * @Description: 删除劳务公司（包含批量删除）
     * @author kan yuanfeng
     * @date 2020/11/04 11:42
     */
    @DeleteMapping
    @ApiOperation("删除劳务公司（包含批量删除）")
    @CommonOperateLogAnnotate(module = LogModule.LABOR_MANAGEMENT, desc = "")
    public RestMessage delBatch(@RequestBody LaborCompanyProject laborCompanyProject) {
        Assert.notEmpty(laborCompanyProject.getIds(), "id不能为空");
        // 记录日志详情
        List<String> companyNames = new ArrayList<>();
        laborCompanyProject.getIds().forEach(p -> {
            LaborCompanyProject company = laborCompanyProjectService.getById(p);
            companyNames.add(company.getCompanyName());
        });
        if (CollectionUtil.isNotEmpty(companyNames)) {
            LogHelper.setContent(LogOperateType.LABOL_COMPANY_DELETE, StringUtil.join(companyNames, ","));
        }
        laborCompanyProjectService.delBatch(laborCompanyProject.getIds());
        return RestBuilders.successBuilder().build();
    }

    /**
     * @Description: 编辑劳务公司
     * @author kan yuanfeng
     * @date 2020/11/04 11:42
     */
    @PutMapping
    @ApiOperation("编辑劳务公司")
    public RestMessage updateById(@RequestBody LaborCompanyProject laborCompanyProject) {
        Assert.notNull(laborCompanyProject.getId(), "id不能为空");
        laborCompanyProjectService.updateOne(laborCompanyProject);
        return RestBuilders.successBuilder().build();
    }

    /**
     * @Description: 进退场
     * @author kan yuanfeng
     * @date 2020/11/04 11:42
     */
    @PutMapping("status")
    @ApiOperation("进退场")
    @CommonOperateLogAnnotate(module = LogModule.LABOR_MANAGEMENT, desc = "")
    public RestMessage updateStatus(@RequestBody LaborCompanyProject laborCompanyProject) {
        Assert.notNull(laborCompanyProject.getId(), "id不能为空");
        // 记录日志详情
        LaborCompanyProject companyProject = laborCompanyProjectService.getById(laborCompanyProject.getId());
        if (null != laborCompanyProject.getStatus() && 0 == laborCompanyProject.getStatus()) {//单位退场
            LogHelper.setContent(LogOperateType.LABOL_COMPANY_EXIT_PROJECT, companyProject.getCompanyName());
        } else {
            LogHelper.setContent(LogOperateType.LABOL_COMPANY_IN_PROJECT, companyProject.getCompanyName());
        }
        laborCompanyProjectService.updateStatus(laborCompanyProject);
        return RestBuilders.successBuilder().build();
    }

    /**
     * @Description: 根据id查询劳务公司详情
     * @author kan yuanfeng
     * @date 2020/11/04 11:42
     */
    @GetMapping("{id}")
    @ApiOperation("根据id查询劳务公司详情")
    public RestMessage findById(@PathVariable("id") String id) {
        Assert.notNull(id, "id不能为空");
        LaborCompanyProject laborCompanyProject = laborCompanyProjectService.getById(id);
        return RestBuilders.successBuilder().data(laborCompanyProject).build();
    }

    /**
     * @Description: 根据条件，分页(不分页)查询
     * @author kan yuanfeng
     * @date 2020/11/04 11:42
     */
    @PostMapping("list")
    @ApiOperation("根据条件，分页(不分页)查询")
    public RestMessage queryListByPage(@RequestBody RequestModel<LaborCompanyProjectDTO> requestModel) {
        Assert.notNull(requestModel.getCustomQueryParams(), "customQueryParams 不能为空");
        Assert.notNull(requestModel.getPage(), "page 不能为空");
        IPage<LaborCompanyProjectDTO> record = laborCompanyProjectService.queryListByPage(requestModel);
        return RestBuilders.successBuilder().data(record).build();
    }

    /**
     * 组成一个树
     */
    @GetMapping("tree")
    public RestMessage getTree(String groupName) {
        List<CompanyTree> companyTreeList = laborCompanyProjectService.getTree(groupName);
        return RestBuilders.successBuilder().data(companyTreeList).build();
    }

    /**
     * 批量导入劳务公司
     * type = 1 为覆盖
     */
    @PostMapping("import")
    @ApiOperation("批量导入")
    public RestMessage importExcel(@NotNull @RequestPart("file") MultipartFile file, Integer type) throws Exception {
        //获取当前时间的时间
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String key = "company:" + formatter.format(calendar.getTime());
        String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
        AsyncUtil.submitTask(key, () -> {
            ExcelResultDTO resultDTO;
            try {
                resultDTO = laborCompanyProjectService.importExcel(file, tenantId, type);
            } catch (Exception e) {
                throw new BusinessException(e.getMessage());
            }
            return resultDTO;
        });
        return RestBuilders.successBuilder().data(key).build();
    }

    /**
     * @Description: 下载模板
     * @author kan yuanfeng
     * @date 2020/11/04 11:42
     */
    @GetMapping("exportTemplate")
    @ApiOperation("下载模板")
    public void exportTemplate(HttpServletRequest request, HttpServletResponse response) {
        String title = "参建单位";
        String fileName = title + ".xls";
        try {
            OutputStream outputStream = OutputStreamUtil
                    .getOutputStream(request, response, fileName);
            String keyValue = "企业名称(必填*):name,统一社会信用代码(必填*):code,承建类型(必填*):buildType,单位简称(必填*):abbreviation,"
                    + "法人姓名:legal,法人电话:legalTelephone";
            ExcelTools
                    .exportExcel(outputStream, keyValue, LaborCompany.creatExcel(), ExcelConstant.XLSX, title);
            response.flushBuffer();
            outputStream.close();
        } catch (IOException e) {
            throw new RuntimeException("excel导出失败！IOException异常");
        } catch (Exception e) {
            throw new RuntimeException("excel导出失败！");
        }
    }

    @GetMapping("/queryCompanySelect")
    @ApiOperation("项目公司下拉框数据")
    public RestMessage queryCompanySelect() {
        return this.laborCompanyProjectService.queryCompanySelect();
    }
}

